package com.huaxindata.im.main.chat;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.upstream.FileDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSink;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;
import com.huaxindata.im.R;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.util.FileUtil;

import java.io.File;

public class VideoPlayerActivity extends AppCompatActivity {
    String url = "http://www.iwatercloud" +
            ".cn:8081/uploads/app/chatModule/2017/9/29/video/video_1506655284059.mp4";
    private SimpleExoPlayerView mPlayerView;
    private SimpleExoPlayer mSimpleExoPlayer;
    private ImageView mImageView;
    private String mUri;
    private int mUrlCategory;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);
        mPlayerView = (SimpleExoPlayerView) findViewById(R.id.main_player_view);
        mImageView= (ImageView) findViewById(R.id.player_first_iv);
        mUri = getIntent().getStringExtra(ImConstants.FILE_URL);
        mUrlCategory = getIntent().getIntExtra(ImConstants.FILE_URL_CATEGORY, 0);
        init();
    }
    private void init() {
        BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        AdaptiveTrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
        DefaultTrackSelector trackSelector = new DefaultTrackSelector
                (videoTrackSelectionFactory);
        mSimpleExoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
        //绑定到view
        mPlayerView.setPlayer(mSimpleExoPlayer);
        //准备player
        if (mUrlCategory == ImConstants.LOCAL_FILE) {
            setLocalSource(mUri);
        } else if (mUrlCategory == ImConstants.REMOTE_FILE) {
            loadCacheSource(mUri);
        }
        mSimpleExoPlayer.addVideoListener(new SimpleExoPlayer.VideoListener() {
            @Override
            public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees,
                                           float pixelWidthHeightRatio) {
                mImageView.setVisibility(View.INVISIBLE);
            }
            @Override
            public void onRenderedFirstFrame() {
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                mPlayerView.setLayoutParams(layoutParams);
            }
        });
    }

    private void setLocalSource(String url){
        DefaultBandwidthMeter defaultBandwidthMeter = new DefaultBandwidthMeter();
        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this,
                Util.getUserAgent(this, "com.huaxin.hxcloud"),defaultBandwidthMeter);
        DefaultExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
        MediaSource videoSource = new ExtractorMediaSource(Uri.parse(url),
                dataSourceFactory, extractorsFactory, null, null);
        mSimpleExoPlayer.prepare(videoSource);
        mSimpleExoPlayer.setPlayWhenReady(true);
    }
    private void loadCacheSource(String url){
        String clientId = getIntent().getStringExtra(ImConstants.CLIENT_ID);
        String cacheDir = FileUtil.getChatFileCacheDir(this, clientId);
        File dir = new File(cacheDir, "video_"+clientId);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        MyCacheDataSourceFactory myCacheDataSourceFactory = new MyCacheDataSourceFactory(this, 1
                << 30, 30 << 10, dir.getPath());
        MediaSource mediaSource = new ExtractorMediaSource(Uri.parse(url),
                myCacheDataSourceFactory, new DefaultExtractorsFactory(), null,null);
        mSimpleExoPlayer.prepare(mediaSource);
        mSimpleExoPlayer.setPlayWhenReady(true);
    }
    private class MyCacheDataSourceFactory implements DataSource.Factory {
        private final Context context;
        private final DefaultDataSourceFactory defaultDatasourceFactory;
        private final long maxFileSize, maxCacheSize;
        private String dir;

        public MyCacheDataSourceFactory(Context context, long maxCacheSize, long maxFileSize,String dir) {
            super();
            this.context = context;
            this.maxCacheSize = maxCacheSize;
            this.maxFileSize = maxFileSize;
            this.dir=dir;
            String userAgent = Util.getUserAgent(context, context.getString(R.string.app_name));
            DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
            defaultDatasourceFactory = new DefaultDataSourceFactory(this.context,
                    bandwidthMeter,
                    new DefaultHttpDataSourceFactory(userAgent, bandwidthMeter));
        }
        @Override
        public DataSource createDataSource() {
            LeastRecentlyUsedCacheEvictor evictor = new LeastRecentlyUsedCacheEvictor(maxCacheSize);
            SimpleCache simpleCache = new SimpleCache(new File(dir), evictor);
            return new CacheDataSource(simpleCache, defaultDatasourceFactory.createDataSource(),
                    new FileDataSource(), new CacheDataSink(simpleCache, maxFileSize),
                    CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR, null);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSimpleExoPlayer.release();
    }
}
